-- 列表
--[[
    参考fgui的列表实现
    列表式在layout的基础上再封装增加额外功能：
    列表中的子元素是同一个元素的克隆
    列表能根据提供的数据数组的长度自动修改子元素个数
    列表能使用itemRenderer来渲染子元素
]]
List = {
    props = {
        _listenItemClick = false
    },
    gets = {
        listenItemClick = function(self)
            return self._listenItemClick
        end
    },
    sets = {
        listenItemClick = function(self, key, val)
            self._listenItemClick = val
            if val then
                for _, v in ipairs(self.children) do
                    v:off(NodeEvent.OnClick, self._onChildClicked, self)
                end
            else
                for _, v in ipairs(self.children) do
                    v:on(NodeEvent.OnClick, self._onChildClicked, self)
                end
            end
        end
    },
    dependencies = {
        Layout
    }
}
local defaultListItemPool = ObjectPool.new(function ()
    return Node.Label("item")
end)
function List:ctor(pool)
    self._itemPool = pool or defaultListItemPool
end
local function getChildIndex(self, child)
    for i = 1, #self.children do
        if child == self.children[i] then
            return i
        end
    end
    return 0
end
function List:_onChildClicked(child)
    local idx = getChildIndex(self, child)
    self:emit(NodeEvent.OnChildClicked, child, idx)
end

function List:onListItemClick(fn, target)
    self:on(NodeEvent.OnChildClicked, fn, target)
end

function List:setListData(data)
    self.data = data
    if #self.children < #data then
        for i = #self.children + 1, #data do
            local item = self._itemPool:get(data[i])
            self:add(item)
            Console.log(item:hasCompoent(Stretch))
            Console.log(item:hasTag("WidthController"))
            if self._listenItemClick then
                self.children[i]:onClick(self._onChildClicked, self)
            end
        end
    elseif #self.children > #data then
        for i = #self.children, #data + 1, -1 do
            self._itemPool:recycle(self.children[i])
            self:removeAt(i)
        end
    end
    for i, v in ipairs(self.children) do
        v:setUIData(data[i], i)
    end
end

function Node.List(params)
    local node = Node.new():addComponent(List, params)
    node.name = "list"
    node.layoutSizeMode = LayoutSizeMode.Stretch
    return node
end